package com.tiance.demo.ui.page;

import com.tiance.demo.observer.ObserverData;
import com.tiance.demo.observer.ObserverEvent;
import com.tiance.demo.observer.ObserverSystem;
import com.tiance.demo.observer.Publisher;
import com.tiance.demo.service.mysql.bo.FileHeader;
import com.tiance.demo.service.mysql.bo.Page;
import com.tiance.demo.service.mysql.constants.FilePageType;
import com.tiance.demo.service.mysql.utils.ByteUtils;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class PageList extends ListView<Page> implements Observer {

    public PageList() {
        this.setCellFactory(new Callback<ListView<Page>, ListCell<Page>>() {
            @Override
            public ListCell call(ListView param) {
                return new ListCell<Page>() {
                    @Override
                    protected void updateItem(Page page, boolean empty) {
                        super.updateItem(page, empty);
                        if (empty) {
                            setText(null);
                            setGraphic(null);
                        } else {
                            FileHeader fileHeader = page.getFileHeader();
                            String type = fileHeader.getType();
                            setText(String.format("%06d", fileHeader.getOffset()) + " - " + FilePageType.getTypeName(ByteUtils.hexStr2Int(type)));
                        }
                    }
                };
            }
        });

        this.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Page>() {
            @Override
            public void changed(ObservableValue<? extends Page> observable, Page oldValue, Page newValue) {
                ObserverData observerData = new ObserverData(newValue);
                ObserverSystem.notifyObservers(ObserverEvent.PAGE_SWITCH, observerData);
            }
        });

        ObserverSystem.registerObserver(ObserverEvent.OPEN_FILE, this);
    }

    @Override
    public void update(Observable o, Object arg) {

        Publisher publisher = (Publisher) o;
        ObserverData transfer = ObserverData.transfer(arg);
        if (publisher.getObserverEvent() == ObserverEvent.OPEN_FILE) {
            List<Page> pages = (List<Page>) transfer.getData();
            this.setItems(FXCollections.observableArrayList(pages));
        }
    }

}
